import React, { useEffect, useRef, useState } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { Breadcrumb, Button, message } from 'antd';
import { ElementType } from './design/config'
import {
  ZoomTool,
  FlowRenderer,
  AddNodeModal,
  EditNodeDrawer,
  LeftMenu,
  ConditionFilterModal,
} from './design';
import { flowDefineService } from '@/flowService';
import { addNode, deleteNode } from './design/operate';
import useFlowStore from './design/hooks/flowStore';
// import { rebuildCondition } from './design/data/generate';
import './flowDesign.scss';

const FlowDesign = () => {
  const params = useParams();
  const navigate = useNavigate();
  const flowContext = useFlowStore();
  const [flowName, setFlowName] = useState('');
  const [scale, setScale] = useState(1);

  const flowCanvasRef = useRef();
  const addNodeModalRef = useRef();
  const editNodeModalRef = useRef();
  const conditionFilterModalRef = useRef();
  const flowRendererRef = useRef();

  const queryFlowDefineInfo = async () => {
    const res = await flowDefineService.getDefineInfo(params.id);
    if (res.success) {
      setFlowName(res.data.flowName);
      flowContext.update(draft => {
        Object.assign(draft, {
          ...res.data,
          flowContent: res.data.flowContent || [],
          flowInputParams: res.data.flowInputParams || [],
          flowOutputParams: res.data.flowOutputParams || [],
          flowVariables: res.data.flowVariables || [],
        });
        draft.flowContent = JSON.parse(res.data.flowContent);
        console.log(draft)
      });
    } else {
      message.error(res.errorMsg);
    }
  };

  const onZoomToolChange = (value) => {
    setScale(flowRendererRef.current.scaleFromTop(value));
  };

  useEffect(() => {
    const init = async () => {
      try {
        await queryFlowDefineInfo();
      } catch (error) {
        console.log(error)
        message.error('流程定义内容解析失败');
        return;
      }
      flowRendererRef.current = new FlowRenderer(flowCanvasRef.current, {
        flowContext: flowContext,
        onZoom: (event) => {
          setScale(event.transform.k);
        },
        onAdd: (d) => {
          console.log(d);
          addNodeModalRef.current.open({
            afterSelect: (info) => {
              addNode({ info, prev: d.data });
              flowRendererRef.current.refresh();
            },
          });
        },
        onEdit: (d) => {
          console.log(d);
          if (d.data.type === ElementType.BRANCH) {
            const data = d.data;
            const parent = data.getParent();
            conditionFilterModalRef.current.open({
              data: parent.raw,
              index: data.branchIndex,
              afterEdit: (val) => {
                if (val) {
                  flowContext.update(draft => {
                    const parentRaw = draft.flowContent.find(item => item.key === parent.key);
                    const branch = parentRaw?.conditions?.[data.branchIndex];
                    if (branch) {
                      branch.conditionName = val.conditionName;
                      branch.conditionExpressions = val.conditionExpressions;
                    }
                  });
                  flowRendererRef.current.refresh();
                }
              },
            });
          } else if (d.data.type === ElementType.CONDITION) {
            editNodeModalRef.current.open({
              data: d.data.raw,
              afterEdit: (oldData) => {
                rebuildCondition(flowContext, d.data, oldData);
                flowRendererRef.current.refresh();
              },
            });
          } else {
            editNodeModalRef.current.open({
              data: d.data.raw,
              afterEdit: () => {
                flowRendererRef.current.refresh();
              },
            });
          }
        },
        onDelete: (d) => {
          console.log(d);
          deleteNode({ current: d.data });
          flowRendererRef.current.refresh();
        },
      });
    };

    init();
  }, []);

  const flowSubmit = () => {
    const { flowContent, flowVariables } = flowContext.data;
    saveFlowDefineContent(JSON.stringify(flowContent), flowVariables);
  };

  const saveFlowDefineContent = async (flowContent, flowVariables) => {
    const res = await flowDefineService.saveFlowContent({
      id: params.flowDefinitionId,
      flowContent: flowContent,
      flowVariables: flowVariables,
    });
    if (res.success) {
      message.success('保存成功');
    } else {
      message.error(res.errorMsg);
    }
  };

  return (
    <div className="page-flow-design">
      <div className="flow-header">
        <Breadcrumb
          items={[
            {
              title: <Link to="/integration/sharing/serviceFlow">服务编排</Link>,
            },
            {
              title: flowName,
            },
          ]}
        />
        <Button className="flow-submit" type="primary" onClick={flowSubmit}>保存</Button>
      </div>
      <div className="flow-canvas" ref={flowCanvasRef}>
        <ZoomTool scale={scale} onChange={onZoomToolChange} />
      </div>
      <LeftMenu />
      <AddNodeModal ref={addNodeModalRef} />
      <EditNodeDrawer ref={editNodeModalRef} />
      <ConditionFilterModal ref={conditionFilterModalRef} />
    </div>
  );
};

export default FlowDesign; 